package com.zxmc.server.service.impl;

import com.aliyun.oss.AliOSSUtils;
import com.zxmc.common.constant.MessageConstant;
import com.zxmc.common.context.BaseContext;
import com.zxmc.common.exception.AccountNotFoundException;
import com.zxmc.common.exception.PasswordErrorException;
import com.zxmc.common.exception.RegisterErrorException;
import com.zxmc.common.exception.UserUpdateException;
import com.zxmc.common.utils.RegularUtil;
import com.zxmc.pojo.dto.UserLoginDto;
import com.zxmc.pojo.entity.User;
import com.zxmc.pojo.vo.UserLoginVO;
import com.zxmc.server.mapper.UserMapper;
import com.zxmc.server.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

import static com.zxmc.common.constant.AvatarConstant.AVATAR_DEFAULT;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FriendService friendService;
    @Autowired
    private ReadingHistoryService readingHistoryService;
    @Autowired
    private BookShelfService bookShelfService;
    @Autowired
    private ChatService chatService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String username) {
        //无登陆状态
        //查找用户
        User user = listByName(username);
        //删除相关的阅读历史
        readingHistoryService.delete(user);
        //删除相关的好友关系
        friendService.deleteCommon(user);
        //删除相关的书架信息
        bookShelfService.deleteByUser(user);
        //删除相关的聊天信息
        chatService.delete(user);
        //删除用户
        userMapper.delete(user);
    }

    @Override
    public User login(UserLoginDto userLoginDto) {
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.list(userLoginDto);

        //2、处理各种异常情况（用户名不存在、密码不对）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的明文密码进行md5加密处理

        //TODO
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }



        //3、返回实体对象
        return user;
    }

    @Override
    public void register(UserLoginDto userLoginDto) {
        if(!RegularUtil.checkName(userLoginDto.getUsername()) || !RegularUtil.checkPwd(userLoginDto.getPassword())) {
            //注册失败
            throw new RegisterErrorException(MessageConstant.REGISTER_FAILED);
        }
        User user = new User();
        BeanUtils.copyProperties(userLoginDto, user);
//        user.setCreatedAt(LocalDateTime.now());
        user.setPassword(DigestUtils.md5DigestAsHex(userLoginDto.getPassword().getBytes()));
        user.setAvatar(AVATAR_DEFAULT);
        userMapper.insert(user);
    }

    @Override
    public User list() {
        Integer userId = BaseContext.getCurrentId();
        return userMapper.listById(userId);
    }

    @Override
    public User listByName(String name) {
        UserLoginDto userLoginDto = new UserLoginDto();
        userLoginDto.setUsername(name);
        return userMapper.list(userLoginDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(User user) {
        User user2 = list();
        user.setId(user2.getId());
//        user.setPassword(user2.getPassword());
        if(user.getPassword()!=null) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        if(user2.equals(user)) {
            throw new UserUpdateException(MessageConstant.USER_UPDATE_SAME);
        }
        User user1 = listByName(user.getUsername());
        if(user1!=null&&!user1.getUsername().equals(user.getUsername())) {
            throw new UserUpdateException(MessageConstant.USER_UPDATE_EXIST);
        }
//        if(user.getAvatar()!=null) {
//            user.setAvatar(user2.getAvatar());
//        }
        userMapper.update(user);
        //修改好友信息
        friendService.update(user);
    }

    @Override
    public void logout() {
        Integer userId = BaseContext.getCurrentId();

    }

    @Override
    public User listById(Integer id) {
        return userMapper.listById(id);
    }

    @Override
    public List<User> listAll() {
        return userMapper.listAll();
    }

    @Override
    public void updateOnly(User user) {
        userMapper.update(user);
    }
}
